package com.dragon.aipictures.test2;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

@Slf4j
@Component
public class HotspotMonitor {
    private static final long THRESHOLD = 1_000_000L;
    @Resource
    private TableSplitter tableSplitter;
    
    @Autowired
    private JdbcTemplate jdbcTemplate;
    
    @Scheduled(fixedDelay = 300_000) // 5分钟检查一次
    public void checkHotSpaces() {
        List<Long> spaceIds = jdbcTemplate.queryForList(
            "SELECT space_id FROM sharding_metadata WHERE table_count=1 AND status='ACTIVE'", 
            Long.class
        );
        
        spaceIds.parallelStream().forEach(spaceId -> {
            long count = jdbcTemplate.queryForObject(
                "SELECT COUNT(*) FROM picture_" + spaceId, 
                Long.class
            );
            
            if (count > THRESHOLD) {
                log.info("检测到热点space: {} 数据量: {}", spaceId, count);
                tableSplitter.splitTable(spaceId);
            }
        });
    }
}